﻿using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Mtool.FSM;
using System.Xml;
using System.Xml.Serialization;
using MToolStudio.Render;
using System.IO;

namespace MToolStudio
{
    [Serializable]
    public class MToolStudioData
    {
        private List<ActionR> actions = new List<ActionR>();
        private List<StateR> states = new List<StateR>();
        private List<FunctionR> functions = new List<FunctionR>();
        private List<TokenImpl> tokens = new List<TokenImpl>();
        private FSM machine;

        [XmlArray]
        public List<ActionR> Actions
        {
            get { return actions; }
            set { actions = value; }
        }

        [XmlArray]
        public List<StateR> States
        {
            get { return states; }
            set { states = value; }
        }

        [XmlArray]
        public List<TokenImpl> Tokens
        {
            get { return tokens; }
            set { tokens = value; }
        }

        [XmlArray]
        public List<FunctionR> Functions
        {
            get { return functions; }
            set { functions = value; }
        }

        [XmlElement]
        public FSM Machine
        {
            get { return machine; }
            set { machine = value; }
        }

        public MToolStudioData()
        {}

        public MToolStudioData(List<IRenderable> uiItems, List<FunctionR> functions, FSM machine)
        {
            foreach(IRenderable r in uiItems)
            {
                if(r is ActionR)
                    actions.Add(r as ActionR);
                else if (r is StateR)
                    states.Add(r as StateR);
                else
                {
                    Logger.Instance.Warn("[save]uiItem with type {0} is ignored", r.GetType().Name);
                }
            }
            this.functions = functions;
            this.machine = machine;
        }

        public void SaveToFile(string filePath)
        {
            using (StreamWriter wter = new StreamWriter(filePath))
            {
                XmlSerializer srlz = new XmlSerializer(GetType());
                srlz.Serialize(wter, this);
            }
        }

        public static MToolStudioData LoadFromFile(string filePath)
        {
            using (StreamReader rder = new StreamReader(filePath))
            {
                XmlSerializer srlz = new XmlSerializer(typeof(MToolStudioData));
                return srlz.Deserialize(rder) as MToolStudioData;
            }
        }
    }
}
